// 定时触发器 - 获取和保存token - 本函数固定公网IP - 生产环境推荐设置间隔小于5分钟获取一次，详见config.json
const cloud = require('wx-server-sdk')
const request = require('request')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database();
const _ = db.command;
const tokens = db.collection("token表");

const gzhAppId = "公众号appid";
const gzhSecret = "公众号secret";
const stable_token_url = 'https://api.weixin.qq.com/cgi-bin/stable_token';


// 云函数入口函数
exports.main = async (event, context) => {
  var tokenObj = await doPost(stable_token_url, {
    grant_type: "client_credential",
    appid: gzhAppId,
    secret: gzhSecret
  });
  if (tokenObj.access_token) {
    var now = new Date();
    // 添加新token
    await tokens.add({
      data: {
        gzhAppId:gzhAppId,
        type: 'stable_token',
        accessToken: tokenObj.access_token,
        createTime: now,
        expiresIn: tokenObj.expires_in
      }
    });
  }
}


async function doPost(url, body) {
  const result = await rp({
    url: url,
    body: body
  });
  return (typeof result.body === 'object') ? result.body : JSON.parse(result.body);
}

const rp = options =>
  new Promise((resolve, reject) => {
    request({
      ...options,
      method: 'POST',
      json: true
    }, (error, response, body) => {
      if (error) {
        reject(error);
      }
      resolve(response);
    });
  });